<template>
	<div class="search-container">
		<el-form ref="searchRef" :model="formModel" :inline="true">
			<el-form-item :label="item.label" :prop="item.prop" v-for="item in options" :key="item.prop">
				<!-- 文本框、下拉框、日期框 -->
				<el-input v-if="item.type === 'input'" v-model="formModel[item.prop]" :disabled="item.disabled"
					:placeholder="item.placeholder" :style="{width: item.width }" clearable></el-input>
				<el-select v-else-if="item.type === 'select'" :style="{width: item.width }" v-model="formModel[item.prop]" :disabled="item.disabled"
					:placeholder="item.placeholder" clearable>
					<el-option v-for="opt in item.opts" :key="opt.value" :label="opt.label" :value="opt.value"></el-option>
				</el-select>
				<el-date-picker v-else-if="item.type === 'date'" type="date" :style="{ width: item.width }" v-model="formModel[item.prop]"
					:value-format="item.format"></el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
				<el-button :icon="Refresh" @click="resetForm(searchRef)">重置</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script lang="ts" setup>
import { FormInstance } from 'element-plus';
import { Search, Refresh } from '@element-plus/icons-vue';
import { PropType, ref, computed, watch } from 'vue';
import { FormOptionList } from '@/types/form-option';
import { RQ, QParam } from '@/types/rq';

const props = defineProps({
	rp: {
		type: Object as PropType<RQ<any>>,
		required: true
	},
	options: {
		type: Array as PropType<Array<FormOptionList>>,
		required: true
	},
	search: {
		type: Function,
		default: () => { }
	}
});

const searchRef = ref<FormInstance>();

// 创建表单模型，用于绑定表单控件
const formModel = ref<Record<string, any>>({});

// 将 rp.where 转换为表单模型
const syncFormModel = () => {
	const whereObj: Record<string, any> = {};
	props.rp.where.forEach(param => {
		whereObj[param.name] = param.value;
	});
	formModel.value = { ...whereObj };
};

// 监听 rp.where 的变化，同步到表单模型
watch(() => props.rp.where, () => {
	syncFormModel();
}, { immediate: true });

// 处理搜索
const handleSearch = () => {
	// 将表单数据转换为 QParam 数组
	const whereParams: QParam[] = [];
	Object.entries(formModel.value).forEach(([key, value]) => {
		if (value !== '' && value !== null && value !== undefined) {
			// 查找对应的选项配置，获取类型
			const option = props.options.find(opt => opt.prop === key);
			whereParams.push({
				name: key,
				value: value,
				type: option?.queryType || 'eq'
			});
		}
	});
	
	// 更新 rp.where
	props.rp.where = whereParams;
	
	// 调用搜索函数
	props.search();
};

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	formModel.value = {};
	
	// 清空 rp.where
	props.rp.where = [];
	
	props.search();
};
</script>

<style scoped>
.search-container {
	padding: 20px 30px 0;
	background-color: #fff;
	margin-bottom: 10px;
	border: 1px solid #ddd;
	border-radius: 5px
}
</style>